package com.xmu.makerspace.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

@RequestMapping("downloadfile")
@RestController
public class FileDownLoadController {
    private String teamFilePath;
    @GetMapping("{teamId}/{filename}")
    public ResponseEntity<byte[]> downloadTeamFile(@PathVariable("teamId") String teamId, @PathVariable("filename") String filename) throws IOException {
//此处设置文件路径
        String filePath = teamFilePath + teamId + "/" + filename;
        File file = new File(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", filename, Charset.forName("utf-8"));//此处最后一个参数是设置编码

//利用FileUtils.readFileToByteArray将文件输出为二进制流
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }

}
